{% extends "base.html" %}

{% block title %}方案管理 - 铃声系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-clock"></i> 方案列表
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between mb-3">
                    <div>
                        <button id="refresh-plans" class="btn btn-outline-secondary">
                            <i class="fas fa-sync"></i> 刷新
                        </button>
                    </div>
                    <div>
                        <button id="add-plan" class="btn btn-primary">
                            <i class="fas fa-plus"></i> 添加方案
                        </button>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th scope="col">#</th>
                                <th scope="col">方案名称</th>
                                <th scope="col">类型</th>
                                <th scope="col">状态</th>
                                <th scope="col">操作</th>
                            </tr>
                        </thead>
                        <tbody id="plans-table-body">
                            <!-- 方案列表将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 方案编辑模态框 -->
<div class="modal fade" id="planModal" tabindex="-1" aria-labelledby="planModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="planModalLabel">新建方案</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="plan-form">
                    <input type="hidden" id="plan-id" value="">
                    <div class="mb-3">
                        <label for="plan-name" class="form-label">方案名称</label>
                        <input type="text" class="form-control" id="plan-name" required>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <i class="fas fa-bell"></i> 铃声时间点
                            <button type="button" class="btn btn-sm btn-success float-end" id="add-bell-time">
                                <i class="fas fa-plus"></i> 添加
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th scope="col">时间</th>
                                            <th scope="col">音频文件</th>
                                            <th scope="col">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="bell-times-table-body">
                                        <!-- 铃声时间点将通过JavaScript动态添加 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="save-plan">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 铃声时间点编辑模态框 -->
<div class="modal fade" id="bellTimeModal" tabindex="-1" aria-labelledby="bellTimeModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="bellTimeModalLabel">编辑铃声时间点</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="bell-time-form">
                    <input type="hidden" id="bell-time-index" value="">
                    <div class="mb-3">
                        <label for="bell-time" class="form-label">时间</label>
                        <div class="row">
                            <div class="col">
                                <select class="form-select" id="bell-hour" required>
                                    {% for i in range(24) %}
                                    <option value="{{ "%02d"|format(i) }}">{{ "%02d"|format(i) }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-auto">
                                <span class="form-control-plaintext">:</span>
                            </div>
                            <div class="col">
                                <select class="form-select" id="bell-minute" required>
                                    {% for i in range(60) %}
                                    <option value="{{ "%02d"|format(i) }}">{{ "%02d"|format(i) }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-auto">
                                <span class="form-control-plaintext">:</span>
                            </div>
                            <div class="col">
                                <select class="form-select" id="bell-second" required>
                                    {% for i in range(60) %}
                                    <option value="{{ "%02d"|format(i) }}">{{ "%02d"|format(i) }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="bell-audio-file" class="form-label">音频文件</label>
                        <div class="input-group">
                            <select class="form-select" id="bell-audio-file" required>
                                <option value="">请选择音频文件</option>
                                <!-- 音频文件选项将通过JavaScript动态加载 -->
                            </select>
                            <button class="btn btn-outline-secondary" type="button" id="refresh-audio-files">
                                <i class="fas fa-sync"></i>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="save-bell-time">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 当前编辑的方案数据
    let currentPlan = {
        id: null,
        name: '',
        bellTimes: []
    };
    
    // 音频文件列表
    let audioFiles = [];
    
    // 加载方案列表
    function loadPlans() {
        fetch('/api/plans')
            .then(response => response.json())
            .then(plans => {
                renderPlans(plans);
            })
            .catch(error => {
                console.error('加载方案列表失败:', error);
                alert('加载方案列表失败: ' + error.message);
            });
    }
    
    // 渲染方案列表
    function renderPlans(plans) {
        const tbody = document.getElementById('plans-table-body');
        tbody.innerHTML = '';
        
        plans.forEach((plan, index) => {
            const status = plan.is_active ? '启用' : '禁用';
            const statusClass = plan.is_active ? 'text-success' : 'text-danger';
            
            const row = document.createElement('tr');
            row.innerHTML = `
                <th scope="row">${index + 1}</th>
                <td>${plan.name}</td>
                <td>${plan.type}</td>
                <td><span class="${statusClass}">${status}</span></td>
                <td>
                    <button class="btn btn-sm btn-outline-primary edit-plan" data-id="${plan.id}">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-outline-danger delete-plan" data-id="${plan.id}" data-name="${plan.name}">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </td>
            `;
            tbody.appendChild(row);
        });
        
        // 绑定编辑和删除按钮事件
        document.querySelectorAll('.edit-plan').forEach(btn => {
            btn.addEventListener('click', function() {
                const planId = this.getAttribute('data-id');
                editPlan(planId);
            });
        });
        
        document.querySelectorAll('.delete-plan').forEach(btn => {
            btn.addEventListener('click', function() {
                const planId = this.getAttribute('data-id');
                const planName = this.getAttribute('data-name');
                deletePlan(planId, planName);
            });
        });
    }
    
    // 添加方案
    function addPlan() {
        currentPlan = {
            id: null,
            name: '',
            bellTimes: []
        };
        
        document.getElementById('planModalLabel').textContent = '新建方案';
        document.getElementById('plan-id').value = '';
        document.getElementById('plan-name').value = '';
        document.getElementById('bell-times-table-body').innerHTML = '';
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('planModal'));
        modal.show();
    }
    
    // 编辑方案
    function editPlan(planId) {
        fetch(`/api/plans/${planId}`)
            .then(response => response.json())
            .then(data => {
                currentPlan = {
                    id: data.plan.id,
                    name: data.plan.name,
                    bellTimes: data.bell_times.map(bt => ({
                        time: bt.time,
                        audioFile: bt.audio_file
                    }))
                };
                
                document.getElementById('planModalLabel').textContent = `编辑方案 - ${data.plan.name}`;
                document.getElementById('plan-id').value = data.plan.id;
                document.getElementById('plan-name').value = data.plan.name;
                
                // 渲染铃声时间点
                renderBellTimes();
                
                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('planModal'));
                modal.show();
            })
            .catch(error => {
                console.error('加载方案详情失败:', error);
                alert('加载方案详情失败: ' + error.message);
            });
    }
    
    // 渲染铃声时间点
    function renderBellTimes() {
        try {
            const tbody = document.getElementById('bell-times-table-body');
            tbody.innerHTML = '';
            
            if (!currentPlan.bellTimes) {
                console.warn('没有铃声时间点数据');
                return;
            }
            
            currentPlan.bellTimes.forEach((bellTime, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${bellTime.time}</td>
                    <td>${bellTime.audioFile}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary edit-bell-time" data-index="${index}">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger delete-bell-time" data-index="${index}">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                `;
                tbody.appendChild(row);
            });
            
            // 绑定编辑和删除按钮事件
            document.querySelectorAll('.edit-bell-time').forEach(btn => {
                btn.addEventListener('click', function() {
                    try {
                        const index = parseInt(this.getAttribute('data-index'));
                        editBellTime(index);
                    } catch (error) {
                        console.error('绑定编辑按钮事件时出错：', error);
                    }
                });
            });
            
            document.querySelectorAll('.delete-bell-time').forEach(btn => {
                btn.addEventListener('click', function() {
                    try {
                        const index = parseInt(this.getAttribute('data-index'));
                        deleteBellTime(index);
                    } catch (error) {
                        console.error('绑定删除按钮事件时出错：', error);
                    }
                });
            });
        } catch (error) {
            console.error('渲染铃声时间点时出错：', error);
            alert('渲染铃声时间点时出错：' + error.message);
        }
    }
    
    // 添加铃声时间点
    function addBellTime() {
        // 加载音频文件列表
        loadAudioFilesForSelect();
        
        // 清空表单
        document.getElementById('bell-time-index').value = '';
        document.getElementById('bell-hour').value = '08';
        document.getElementById('bell-minute').value = '00';
        document.getElementById('bell-second').value = '00';
        document.getElementById('bell-audio-file').value = '';
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('bellTimeModal'));
        modal.show();
    }
    
    // 编辑铃声时间点
    function editBellTime(index) {
        try {
            console.log('编辑铃声时间点，索引：', index);
            console.log('当前方案：', currentPlan);
            
            if (!currentPlan.bellTimes || index >= currentPlan.bellTimes.length) {
                console.error('无效的铃声时间点索引：', index);
                alert('无法编辑铃声时间点：数据错误');
                return;
            }
            
            const bellTime = currentPlan.bellTimes[index];
            console.log('铃声时间点数据：', bellTime);
            
            // 加载音频文件列表
            loadAudioFilesForSelect();
            
            // 解析时间
            const timeParts = bellTime.time.split(':');
            const hour = timeParts[0] || '08';
            const minute = timeParts[1] || '00';
            const second = timeParts[2] || '00';
            
            // 填充表单
            document.getElementById('bell-time-index').value = index;
            document.getElementById('bell-hour').value = hour;
            document.getElementById('bell-minute').value = minute;
            document.getElementById('bell-second').value = second;
            document.getElementById('bell-audio-file').value = bellTime.audioFile;
            
            // 显示模态框
            const modalElement = document.getElementById('bellTimeModal');
            console.log('模态框元素：', modalElement);
            
            if (!modalElement) {
                console.error('无法找到模态框元素');
                alert('无法找到模态框元素');
                return;
            }
            
            const modal = new bootstrap.Modal(modalElement);
            console.log('模态框实例：', modal);
            modal.show();
        } catch (error) {
            console.error('编辑铃声时间点时出错：', error);
            alert('编辑铃声时间点时出错：' + error.message);
        }
    }
    
    // 删除铃声时间点
    function deleteBellTime(index) {
        if (confirm('确定要删除这个铃声时间点吗？')) {
            currentPlan.bellTimes.splice(index, 1);
            renderBellTimes();
        }
    }
    
    // 保存铃声时间点
    function saveBellTime() {
        try {
            const index = document.getElementById('bell-time-index').value;
            const hour = document.getElementById('bell-hour').value;
            const minute = document.getElementById('bell-minute').value;
            const second = document.getElementById('bell-second').value;
            const audioFile = document.getElementById('bell-audio-file').value;
            
            // 验证表单
            if (!audioFile) {
                alert('请选择音频文件');
                return;
            }
            
            const bellTime = {
                time: `${hour}:${minute}:${second}`,
                audioFile: audioFile
            };
            
            if (index === '') {
                // 添加新的铃声时间点
                currentPlan.bellTimes.push(bellTime);
            } else {
                // 更新现有的铃声时间点
                const idx = parseInt(index);
                if (idx >= 0 && idx < currentPlan.bellTimes.length) {
                    currentPlan.bellTimes[idx] = bellTime;
                } else {
                    console.error('无效的铃声时间点索引：', idx);
                    alert('无法保存铃声时间点：索引错误');
                    return;
                }
            }
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('bellTimeModal'));
            modal.hide();
            
            // 重新渲染铃声时间点列表
            renderBellTimes();
        } catch (error) {
            console.error('保存铃声时间点时出错：', error);
            alert('保存铃声时间点时出错：' + error.message);
        }
    }
    
    // 删除方案
    function deletePlan(planId, planName) {
        if (confirm(`确定要删除方案 "${planName}" 吗？\n注意：此操作将同时删除该方案下的所有铃声时间点。`)) {
            fetch(`/api/plans/${planId}`, {
                method: 'DELETE'
            })
            .then(response => {
                if (response.ok) {
                    alert('方案删除成功');
                    loadPlans(); // 重新加载方案列表
                } else {
                    throw new Error('删除方案失败');
                }
            })
            .catch(error => {
                console.error('删除方案失败:', error);
                alert('删除方案失败: ' + error.message);
            });
        }
    }
    
    // 保存方案
    function savePlan() {
        const planName = document.getElementById('plan-name').value.trim();
        
        // 验证表单
        if (!planName) {
            alert('请输入方案名称');
            return;
        }
        
        if (planName.length > 50) {
            alert('方案名称不能超过50个字符');
            return;
        }
        
        if (currentPlan.bellTimes.length === 0) {
            if (!confirm('该方案没有设置铃声时间点，确定要保存吗？')) {
                return;
            }
        }
        
        // 准备数据
        const planData = {
            name: planName,
            type: 'custom',
            is_active: true
        };
        
        if (currentPlan.id) {
            // 更新现有方案
            fetch(`/api/plans/${currentPlan.id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(planData)
            })
            .then(response => {
                if (response.ok) {
                    // 更新铃声时间点
                    return updateBellTimes(currentPlan.id);
                } else {
                    throw new Error('更新方案失败');
                }
            })
            .then(() => {
                alert('方案更新成功');
                const modal = bootstrap.Modal.getInstance(document.getElementById('planModal'));
                modal.hide();
                loadPlans(); // 重新加载方案列表
            })
            .catch(error => {
                console.error('更新方案失败:', error);
                alert('更新方案失败: ' + error.message);
            });
        } else {
            // 创建新方案
            fetch('/api/plans', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(planData)
            })
            .then(response => {
                if (response.ok) {
                    return response.json();
                } else {
                    throw new Error('创建方案失败');
                }
            })
            .then(data => {
                // 保存铃声时间点
                return saveBellTimes(data.id);
            })
            .then(() => {
                alert('方案创建成功');
                const modal = bootstrap.Modal.getInstance(document.getElementById('planModal'));
                modal.hide();
                loadPlans(); // 重新加载方案列表
            })
            .catch(error => {
                console.error('创建方案失败:', error);
                alert('创建方案失败: ' + error.message);
            });
        }
    }
    
    // 保存铃声时间点
    function saveBellTimes(planId) {
        const promises = currentPlan.bellTimes.map(bellTime => {
            return fetch('/api/bell_times', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    plan_id: planId,
                    time: bellTime.time,
                    bell_type: 'default',
                    audio_file: bellTime.audioFile,
                    volume: 80
                })
            });
        });
        
        return Promise.all(promises);
    }
    
    // 更新铃声时间点
    function updateBellTimes(planId) {
        // 先删除所有现有的铃声时间点
        return fetch(`/api/plans/${planId}/bell_times`, {
            method: 'DELETE'
        })
        .then(() => {
            // 然后保存新的铃声时间点
            return saveBellTimes(planId);
        });
    }
    
    // 加载音频文件列表用于选择
    function loadAudioFilesForSelect() {
        fetch('/api/audio_files')
            .then(response => response.json())
            .then(files => {
                audioFiles = files;
                const select = document.getElementById('bell-audio-file');
                select.innerHTML = '<option value="">请选择音频文件</option>';
                
                files.forEach(file => {
                    const option = document.createElement('option');
                    option.value = file.filename;
                    option.textContent = file.filename;
                    select.appendChild(option);
                });
            })
            .catch(error => {
                console.error('加载音频文件列表失败:', error);
            });
    }
    
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 加载方案列表
        loadPlans();
        
        // 绑定按钮事件
        document.getElementById('refresh-plans').addEventListener('click', loadPlans);
        document.getElementById('add-plan').addEventListener('click', addPlan);
        document.getElementById('add-bell-time').addEventListener('click', addBellTime);
        document.getElementById('save-plan').addEventListener('click', savePlan);
        document.getElementById('save-bell-time').addEventListener('click', saveBellTime);
        document.getElementById('refresh-audio-files').addEventListener('click', loadAudioFilesForSelect);
    });
</script>
{% endblock %}